package com.atguigu.champter7.state;

import org.apache.flink.api.common.state.BroadcastState;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.common.state.ReadOnlyBroadcastState;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.BroadcastStream;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.co.BroadcastProcessFunction;
import org.apache.flink.util.Collector;

public class Flink03_Operator_BroadCastState {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("reset.port",9999);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(2);
        env.enableCheckpointing(3000);// 开启checkpoint, 周期是3000ms. 默认checkpoint的地址: JobManager的内存

        DataStreamSource<String> dataStream = env.socketTextStream("hadoop104", 9999);
        DataStreamSource<String> controlStream = env.socketTextStream("hadoop104", 8888);
        MapStateDescriptor<String, String> mapDesc = new MapStateDescriptor<>("controlState", String.class, String.class);
        // 1. 先把控制流做成广播流
        BroadcastStream<String> bcStream = controlStream.broadcast(mapDesc);

        dataStream.connect(bcStream)
                .process(new BroadcastProcessFunction<String, String, String>() {
                    @Override
                    public void processElement(String value,
                                               ReadOnlyContext ctx,
                                               Collector<String> out) throws Exception {
                        ReadOnlyBroadcastState<String, String> broadcastState = ctx.getBroadcastState(mapDesc);
                        String s = broadcastState.get("switch");
                        if ("1".equals(s)){
                            System.out.println("111111111111111");
                        }else if ("2".equals(s)){
                            System.out.println("2222222222");
                        }else {
                            System.out.println("3333333333333");
                        }
                    }

                    @Override
                    public void processBroadcastElement(String value,
                                                        Context ctx,
                                                        Collector<String> out) throws Exception {
                        BroadcastState<String, String> broadcastState = ctx.getBroadcastState(mapDesc);
                        broadcastState.put("switch",value);
                    }
                }).print();
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
